<template>
  <div class="roles-view page-view">
    <!-- 页面标题和操作按钮 -->
    <div class="header-section">
      <h2>角色管理</h2>
      <el-button type="primary" @click="handleCreate" :icon="Plus"> 添加角色 </el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-input
        v-model="searchQuery"
        placeholder="输入角色名称进行模糊搜索..."
        clearable
        class="w-300"
        @input="handleSearch"
        @clear="handleSearchClear"
      >
        <template #prefix>
          <Search />
        </template>
      </el-input>
    </div>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table :data="roleStore.roles" :loading="roleStore.loading" stripe style="width: 100%" empty-text="暂无数据">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" min-width="120" />
        <el-table-column label="用户数量" width="100" align="center">
          <template #default="{ row }">
            <el-tag size="small">{{ row.users?.length || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ row.createdAt ? formatDate(row.createdAt) : "-" }}
          </template>
        </el-table-column>
        <el-table-column prop="updatedAt" label="更新时间" width="180">
          <template #default="{ row }">
            {{ row.updatedAt ? formatDate(row.updatedAt) : "-" }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="260" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="small" :icon="View" @click="handleView(row)">查看</el-button>
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 错误提示 -->
    <el-alert
      v-if="roleStore.error"
      :title="roleStore.error"
      type="error"
      show-icon
      closable
      @close="roleStore.clearError"
      style="margin-top: 16px"
    />

    <!-- 新增角色对话框 -->
    <CreateRoleDialog v-model="showCreateDialog" @success="handleCreateSuccess" />

    <!-- 编辑角色对话框 -->
    <EditRoleDialog v-model="showEditDialog" :role="selectedRole" @success="handleEditSuccess" />
    <ViewRoleDialog v-model="showViewDialog" :role-id="selectedRole?.id" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Search, View } from "@element-plus/icons-vue";
import { useRoleStore } from "@/stores/role";
import type { Role } from "@/types/role";
import CreateRoleDialog from "./components/CreateRoleDialog.vue";
import EditRoleDialog from "./components/EditRoleDialog.vue";
import ViewRoleDialog from "./components/ViewRoleDialog.vue";

defineOptions({
  name: "RolesView",
});

// Store
const roleStore = useRoleStore();

// 本地状态管理
const searchQuery = ref("");
const showCreateDialog = ref(false);
const showEditDialog = ref(false);
const showViewDialog = ref(false);
const selectedRole = ref<Role | null>(null);
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0,
});

// 搜索防抖
let searchTimer: NodeJS.Timeout | null = null;

// 生命周期
onMounted(() => {
  loadRoles();
});

// 加载角色数据
const loadRoles = async () => {
  try {
    const params = {
      page: pagination.value.page,
      pageSize: pagination.value.pageSize,
      name: searchQuery.value || undefined,
    };
    await roleStore.fetchRoles(params);
    // 更新分页信息
    pagination.value.total = roleStore.total;
    pagination.value.page = roleStore.currentPage;
    pagination.value.pageSize = roleStore.pageSize;
  } catch (error) {
    console.error("Failed to load roles:", error);
  }
};

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString("zh-CN");
};

// 搜索处理（防抖）
const handleSearch = () => {
  if (searchTimer) {
    clearTimeout(searchTimer);
  }
  searchTimer = setTimeout(() => {
    pagination.value.page = 1; // 搜索时重置到第一页
    loadRoles();
  }, 500);
};

// 清空搜索
const handleSearchClear = () => {
  searchQuery.value = "";
  pagination.value.page = 1;
  loadRoles();
};

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.page = 1; // 重置到第一页
  loadRoles();
};

const handleCurrentChange = (page: number) => {
  pagination.value.page = page;
  loadRoles();
};

// CRUD操作
const handleCreate = () => {
  showCreateDialog.value = true;
};

const handleCreateSuccess = () => {
  showCreateDialog.value = false;
  // 创建成功后重新加载角色列表
  loadRoles();
};

const handleView = (role: Role) => {
  selectedRole.value = role;
  showViewDialog.value = true;
};

const handleEdit = (role: Role) => {
  selectedRole.value = role;
  showEditDialog.value = true;
};

const handleEditSuccess = () => {
  showEditDialog.value = false;
  selectedRole.value = null;
  // 编辑成功后重新加载角色列表
  loadRoles();
};

const handleDelete = async (role: Role) => {
  try {
    await ElMessageBox.confirm(`确定要删除角色 "${role.name}" 吗？此操作不可恢复。`, "确认删除", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    await roleStore.deleteRole(role.id);
    ElMessage.success("删除成功");
    // 删除后重新加载当前页数据
    loadRoles();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};
</script>

<style lang="scss" scoped>
.roles-view {
  padding: 24px;

  .header-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    h2 {
      margin: 0;
      color: #303133;
      font-weight: 600;
    }
  }

  .search-section {
    margin-bottom: 16px;
  }

  .table-card {
    .pagination-section {
      display: flex;
      justify-content: flex-end;
      margin-top: 16px;
    }
  }
}
</style>
